//
//  CMViewStore.swift
//  covermedia
//
//  Created by travel on 16/8/22.
//  Copyright © 2016年 covermedia. All rights reserved.
//

import UIKit

private extension UIView {
    var cmStoreKey:String {
        return "\(UInt(bitPattern: ObjectIdentifier(self)))"
    }
}

/// View仓库：管理view的显示和隐藏
open class CMViewStore {
    fileprivate var viewStore:[String: CMWeakRef<UIView>] = [:]
    
    public init() {
    }
    deinit {
        for (_, v) in viewStore {
            v.value?.removeFromSuperview()
        }
        viewStore = [:]
    }
    
    fileprivate func clearInvalidViews() {
        var validViews:[String: CMWeakRef<UIView>] = [:]
        for (k, v) in viewStore {
            if let _ = v.value {
                validViews[k] = v
            }
        }
        viewStore = validViews
    }
    
    public func view(inView view:UIView? = nil) -> UIView? {
        guard let cv = view ?? UIApplication.shared.keyWindow else {
            return nil
        }
        return viewStore[cv.cmStoreKey]?.value
    }
    
    /**
     隐藏views容器中的的view
     
     - parameter view: 容器view
     
     - returns: 被移除的view
     */
    public func hideView(inView view:UIView? = nil) -> UIView? {
        guard let cv = view ?? UIApplication.shared.keyWindow else {
            return nil
        }
        let key = cv.cmStoreKey
        let pre = viewStore.removeValue(forKey: key)
        pre?.value?.removeFromSuperview()
        return pre?.value
    }
    /**
     在指定的view中显示内容，默认是居中的
     
     - parameter view:        需要显示的view
     - parameter inView:      待显示view的容器view
     - parameter removePre:   是否删除容易view中以前添加的view
     - parameter layoutBlock: 布局block
     */
    public func showView<T:UIView>(_ view:T,
                  inView:UIView? = nil,
                  removePre:Bool = true,
                  layoutBlock:((_ view:T, _ container:UIView) -> Void)? = nil) {
        clearInvalidViews()
        if removePre {
            _ = hideView(inView: inView)
        }
        
        
        guard let cv = inView ?? UIApplication.shared.keyWindow else {
            return
        }
        
        cv.addSubview(view)
        view.layer.zPosition = 10000
        if let layoutBlock = layoutBlock {
            layoutBlock(view, cv)
        } else {
            if cv.translatesAutoresizingMaskIntoConstraints {
                view.frame = cv.bounds
                cv.autoresizingMask = [.flexibleWidth, .flexibleHeight]
            } else {
                let l = NSLayoutConstraint.init(item: view, attribute: .left, relatedBy: .equal, toItem: cv, attribute: .top, multiplier: 1, constant: 0)
                let r = NSLayoutConstraint.init(item: view, attribute: .right, relatedBy: .equal, toItem: cv, attribute: .top, multiplier: 1, constant: 0)
                let t = NSLayoutConstraint.init(item: view, attribute: .top, relatedBy: .equal, toItem: cv, attribute: .top, multiplier: 1, constant: 0)
                let b = NSLayoutConstraint.init(item: view, attribute: .bottom, relatedBy: .equal, toItem: cv, attribute: .top, multiplier: 1, constant: 0)
                cv.addConstraints([l, r, t, b])
            }
        }
        viewStore[cv.cmStoreKey] = CMWeakRef.init(value: view)
    }
}
